//
//  HomeViewController.swift
//  CBWWeiBo
//
//  Created by 陈博文 on 16/1/7.
//  Copyright © 2016年 陈博文. All rights reserved.
//

import UIKit
import SDWebImage

class HomeViewController: BaseTableViewController {
   // MARK:=============== 定义数组 ===============
    /// 保存所有微博数据
//    var statuses: [StatusViewModel]?
    var statusListModel: StatusListModel = StatusListModel()
    
    // MARK:=============== 懒加载 button ===============
    lazy var titleButton:TitleButton = {
        
        let titleButton = TitleButton()
        
        titleButton.addTarget(self, action: "titleButtonClick:", forControlEvents: .TouchUpInside)
        return titleButton
        
    }()
    // MARK:=============== 懒加载 popver ===============
    
    lazy var popoverAnimator:PopoverAnimator = {
        
        let popoverAnimator = PopoverAnimator()
        let w : CGFloat = 180
        let h : CGFloat = 250
        let x = (self.view.bounds.size.width - w) * 0.5
        let y : CGFloat = 56
        
        popoverAnimator.presentedFrame = CGRectMake(x, y, w, h)
        return popoverAnimator
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupRotate()
        //判断是否已经登录了,如果没有登陆,直接退出
        if !isLogin {
            return
        }

        setupNaviBar()
        setupNotification()
        loadHomeViewControllerData()
        
        // 设置自动计算行高
        // 1.预估行高 --> 提高性能
        tableView.estimatedRowHeight = 200
        // 2.告诉系统需要系统自动计算行高
//        tableView.rowHeight = 600//UITableViewAutomaticDimension
    }
    
 private   func setupNaviBar(){
    
    // 1.创建btn
    navigationItem.leftBarButtonItem = UIBarButtonItem(customView: UIButton(imageName: "navigationbar_friendattention", target: self, action: "leftButtonClick"))
    
    // 2.初始化右侧的Item
    navigationItem.rightBarButtonItem = UIBarButtonItem(customView: UIButton(imageName: "navigationbar_pop", target: self, action: "rightButtonClick"))
    
    //3.设置中间的 title
  
    titleButton.setTitleColor(UIColor.blackColor(), forState: .Normal)
    titleButton.setImage(UIImage(named: "navigationbar_arrow_down"), forState: .Normal)
    titleButton.setImage(UIImage(named: "navigationbar_arrow_up"), forState: .Selected)
    titleButton.setTitle("CBW", forState: .Normal)
    navigationItem.titleView = titleButton
    titleButton.sizeToFit()

    }
    
    // MARK:=============== 设置 notifacation ===============
    func setupNotification(){
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "pressentedViewClick", name: CBWPopoverPresentedViewNoification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "dismissedViewClick", name: CBWPopoverDismissedViewNoification, object: nil)
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }

    // MARK:=============== 设置左右 button 监听方法 ===============
 @objc   private func leftButtonClick(){
    print("leftButtonClick")
    }
 @objc   private func rightButtonClick(){
    
    let QRVC = UIStoryboard(name: "QRCode", bundle: nil)
    presentViewController(QRVC.instantiateInitialViewController()!, animated: true, completion: nil)
    
        }
    @objc   private func titleButtonClick(titleButton:TitleButton){
        
        //VC 的 xib 加载可以省略 loadBundle 这一步
        let popover = PopoverViewController()
        popover.modalPresentationStyle = UIModalPresentationStyle.Custom
        // 3.2.设置转场代理(通过转场代理自定义转场)
        popover.transitioningDelegate = popoverAnimator
        //设置 pressent 一定要放在最后面
        presentViewController(popover, animated: true, completion: nil)
    }
    
     // MARK:=============== 设置监听 button  ===============
  @objc private func pressentedViewClick(){
    
    titleButton.selected = !titleButton.selected
    
    }
    @objc private func dismissedViewClick(){
        
     titleButton.selected = !titleButton.selected
    }
    // MARK:=============== 加载数据 ===============
    private func loadHomeViewControllerData(){
    
        statusListModel.loadData { (models, error) -> () in
            if error != nil
            {
                // 提醒用户
                return
            }
            
            self.tableView.reloadData()
        }
    }
    
   }


extension HomeViewController
{// MARK:=============== datasource ===============
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statusListModel.statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("homeCell", forIndexPath: indexPath) as! HomeTableViewCell
                
        cell.viewModel = statusListModel.statuses![indexPath.row]
        
        return cell
    }
    // MARK:=============== delegate ===============
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        // 1.获取对应行的cell
        // 注意点: 在返回高度的代理方法中, 不能通过带indexPath的方法获取cell, 会导致死循环
        //        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableViewCell.identifier(), forIndexPath: indexPath) as! HomeTableViewCell
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableViewCell.identifier()) as! HomeTableViewCell
        
        // 2.获取对应行的模型
        let viewModel = statusListModel.statuses![indexPath.row]
        
        // 3.计算对应行的高度
        let height = cell.calculateRowHeight(viewModel)
        
        // 4.返回对应行的高度
        return height
    }

}
